import { message } from "antd";
import { GetFieldDecoratorOptions } from "antd/lib/form/Form";
import { addon, getObject, IPermissionService, IRoleService, log, Permission, Ref } from "pao-aop";
import { reactControl, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import FormCreator, { InputType } from "src/business/components/buss-components/form-creator";
import { isPermission } from "src/projects/app/permission";
import { edit_props_info } from "src/projects/app/util-tool";
import { IUserService, User } from "src/projects/models/user";
import { ROUTE_PATH } from "src/projects/router";
import { AppServiceUtility } from "src/projects/app/appService";

/**
 * 组件：名称状态
 */
export interface UserEditorViewState extends ReactViewState {
    /** 用户信息数据 */
    base_data: any;
    /** 角色列表 */
    role_list: any[];
    /** 是否新增角色 */
    isadd?: boolean;
    /** 是否显示新增编辑企业按钮 */
    is_show?: boolean;
    /** 滚动条 */
    loading?: boolean;
}

/**
 * 组件：名称
 */
export class UserEditorView extends React.Component<UserEditorViewControl, UserEditorViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            base_data: [],
            role_list: [],
            isadd: false,
            is_show: false,
            loading: false
        };
    }

    /** 初始化服务 */
    userService?() {
        return getObject(this.props.userService_Fac!);
    }
    /** 权限服务 */
    permissionService?() {
        return getObject(this.props.permissionService_Fac!);
    }
    roleService?() {
        return getObject(this.props.roleService_Fac!);
    }
    componentDidMount() {
        this.setState({
            loading: true
        });
        this.roleService!()!.get_role_list!({}, 1, 10)!
            .then((data: any) => {
                console.info(data);
                if (data !== '无查询结果') {
                    let role_list = [];
                    for (let i = 0; i < data.result.length; i++) {
                        let role = {
                            id: data.result[i]['id'],
                            name: data.result[i]['role_name']
                        };
                        role_list.push(role);
                    }
                    this.setState({
                        role_list: role_list,
                        loading: false
                    });
                }

            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("userEditorViewControl", error.message);
            });
        let id = this.props.match!.params.key;
        this.setState({
            isadd: !this.props.match!.params.key,
        });
        if (id) {
            this.setState({
                loading: true
            });
            this.userService!()!.get_user_by_id!(id)!
                .then((data: any) => {
                    this.setState({
                        base_data: data,
                        is_show: true,
                        loading: false
                    });
                })
                .catch(error => {
                    this.setState({
                        loading: false
                    });
                    log("userEditorViewControl", error.message);
                });
        }

    }
    /** 确定回调 */
    handleSubmit = (err: Error, values: User) => {
        this.setState({
            loading: true
        });
        console.log('submit:', values);
        let datas = {

            account: values.account,
            comment: values.comment || '',
            id: values.id,
            name: values.name,
            role_id: values.role_id
        };
        this.userService!()!.update!(datas)!
            .then((data: any) => {

                if (data === 'Success') {
                    message.info('保存成功！');
                    this.setState({
                        is_show: true,
                    });
                    this.props.history!.push(ROUTE_PATH.userManage);
                } else {
                    message.info(data);
                }
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("userEditorViewControl", error.message);
            });
    }
    reset_password = (id: string) => {
        this.setState({
            loading: true
        });
        this.userService!()!.reset_password!(id)!
            .then((data: any) => {
                this.setState({
                    loading: false
                });
                if (data === 'Success') {
                    message.info('重置密码成功');
                } else {
                    message.info('重置密码失败');
                }
            })
            .catch(error => {
                // debugger;
                this.setState({
                    loading: false
                });
                log("userEditorViewControl", error.message);
            });

    }
    returnBtn = () => {
        this.props.history!.push(ROUTE_PATH.userManage);
    }
    render() {
        const redeirect = isPermission(this.props.permission!);
        if (redeirect) {
            return redeirect;
        }
        let base_data = this.state.base_data;
        let id = this.props.match!.params.key;
        let { role_list } = this.state;

        let edit_props = {
            form_items_props: [
                {
                    title: "用户信息",
                    need_card: true,
                    input_props: [
                        {
                            type: InputType.antd_input,
                            label: "用户名称",
                            decorator_id: "name",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入用户名称" }],
                                initialValue: base_data ? base_data.name : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入用户名称"
                            }
                        },
                        {
                            type: InputType.antd_input,
                            label: "登录账号",
                            decorator_id: "account",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入登录账号" }],
                                initialValue: base_data ? base_data.account : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入登录账号"
                            }
                        },
                        {
                            type: InputType.antd_input,
                            label: "手机号码",
                            decorator_id: "mobile",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入手机号码" }],
                                initialValue: base_data ? base_data.mobile : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入手机号码"
                            }
                        },
                        {
                            type: InputType.antd_input,
                            label: "电子邮箱",
                            decorator_id: "email",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入电子邮箱" }],
                                initialValue: base_data ? base_data.email : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入电子邮箱"
                            }
                        },
                        {
                            type: InputType.antd_input,
                            label: "登录密码",
                            decorator_id: "password",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入登录密码" }],
                                initialValue: id ? '******' : base_data ? base_data.password : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入登录密码",
                                type: 'password'
                            }
                        },
                        {
                            type: InputType.checkbox_group,
                            label: "角色",
                            decorator_id: "role_id",
                            field_decorator_option: {
                                rules: [{ required: true, message: "选择角色" }],
                                initialValue: base_data ? base_data.role_id : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                list: role_list
                            }
                        },
                        {
                            type: InputType.text_area,
                            label: "说明",
                            decorator_id: "comment",
                            field_decorator_option: {
                                initialValue: base_data ? base_data.comment : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入说明",
                                rows: 4
                            }
                        },
                    ]
                }
            ],
            other_btn_propps: [
                {
                    text: "返回",
                    cb: () => {
                        console.log("返回回调");
                        this.props.history!.push(ROUTE_PATH.userManage);
                    }
                }
            ],
            submit_btn_propps: {
                text: "保存",
                cb: this.handleSubmit
            },
            service_option: {
                service_object: AppServiceUtility.user_service,
                operation_option: {
                    save: {
                        func_name: "update",
                    }
                },
            },
            // succ_func: () => { this.props.history!.push(ROUTE_PATH.changepayment); },
            id: this.props.match!.params.key,
        };
        let edit_props_list = Object.assign(edit_props, edit_props_info);
        return (
            <FormCreator {...edit_props_list} />
        );
    }
}

/**
 * 控件：用户编辑控件
 * @description 控制用户编辑控件
 * @author
 */
@addon('UserEditorView', '设备编辑控件', '控制设备编辑控件')
@reactControl(UserEditorView, true)
export class UserEditorViewControl extends ReactViewControl {
    /** 用户服务 */
    public userService_Fac?: Ref<IUserService>;
    /** 权限服务接口 */
    public permissionService_Fac?: Ref<IPermissionService>;
    /** 角色服务 */
    public roleService_Fac?: Ref<IRoleService>;
    /** 视图权限 */
    public permission?: Permission;

}